/**
 * MIT License
 * Copyright (c) 2018 yadong.zhang
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.xuyiwei.xblog.config.server;

import com.xuyiwei.xblog.core.util.WebSocketUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2018/4/18 11:48
 * @since 1.0
 * 虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
 */
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebsocketServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);

    /**
     * 线程安全的socket集合
     * long里面放置的是用户id(里面放置的是登录过的用户)
     */
    private static ConcurrentHashMap<Long,Session> clients = new ConcurrentHashMap<>();

    /**
     * 里面放置的是游客的session
     *
     */
    private static CopyOnWriteArraySet<Session> visitorSessions = new CopyOnWriteArraySet<>();
    /**
     * 初始在线人数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId")Long userId, Session session) {
        this.session = session;
        //如果userId是游客 则放置进
        if(userId==-1l){
            visitorSessions.add(session);
        }else{
            clients.put(userId, session);
        }

        int count = onlineCount.incrementAndGet();
        logger.info("有链接加入，当前在线人数为: {}", count);

        WebSocketUtil.sendOnlineMsg(Integer.toString(count), clients,visitorSessions);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userId")Long userId) {
        int count = onlineCount.decrementAndGet();
        //如果userId是游客 则放置进
        if(userId==-1l){
            visitorSessions.remove(this.session);
        }else{
            //从session中移除
            clients.remove(userId);
        }

        logger.info("有链接关闭,当前在线人数为: {}", count);
        WebSocketUtil.sendOnlineMsg(Integer.toString(count), clients,visitorSessions);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     * 客户端发送过来的消息
     *
     * 只有前端js websocket.send(JSON.stringify(message));发送的消息才会进入这里
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        for(Map.Entry<Long, Session> entry:clients.entrySet()){
            logger.info("session.id={}", session.getId());
            if(session.getId().equals(entry.getValue().getId())){
                logger.info("{}发来消息", entry.getKey());
            }
            break;
        }
        logger.info("接收到消息：{}", message);

    }



    /**
     * 获取在线用户数量
     *
     * @return
     */
    public int getOnlineUserCount() {
        return onlineCount.get();
    }

    /**
     * 获取在线用户的会话信息
     *
     * @return
     */
    public ConcurrentHashMap<Long,Session> getOnlineUsers() {
        return clients;
    }

    /**
     * 获取在线游客的会话信息
     *
     * @return
     */
    public CopyOnWriteArraySet<Session> getOnlineVistors() {
        return visitorSessions;
    }
}
